let path = require("path");
let express = require("express");
let bodyParser = require("body-parser");
let app = express();
let multer = require("multer");
let {
    signAdd
} = require("./login/user_add.js");
let {
    login
} = require("./login/login.js");
let {
    fileFun
} = require("./upload/file.js");
let {
    userChage
} = require("./user/updata.js");
let {
    datumChange
} = require("./user/datumChange.js");
let {
    logFun
} = require("./message/log.js");
let {
    logFind
} = require("./message/logFind");
let {
    addFun
} = require("./data/add.js");
let {
    getData
} = require("./data/getData.js");
let {
    changeFun
} = require("./data/dataChange.js");
let {
    removeFun
} = require("./data/remove.js");
let {
    removeUser
} = require("./user/remove.js");
let {
    getImage
} = require("./upload/getImage.js");
let {
    expenseAdd
} = require("./expense/add.js");
let {
    getExpense
} = require("./expense/getExpense.js");
let {
    integralChange
} = require("./user/integralChange.js");
let {
    userFind
} = require("./user/userFind.js");
let {
    changeControl
} = require("./control/changeControl.js");
let { changeMsg } = require("./system_msg/chageSystemMsg.js");
let { msgFun } = require("./chat/addMsg.js")
let { getSysList } = require("./system_msg/getSystemMsg.js");
let { addSystem } = require("./system_msg/addMsg.js");
let { addLove } = require("./love/addLove.js");
let { getLove } = require("./love/getLove.js");
let { delLove } = require("./love/deleteLove.js");
let { changeLove } = require("./love/changeLove.js");
let { findToken } = require("./token/findToken.js");
let { deleteToken } = require("./token/delToken.js");
let {addError} = require("./error/add_error.js");
let serve = require("http").createServer(app);


// 聊天模块---->
// 跨域处理
let origin = "http://localhost:8080";

// let origin = "http://119.45.124.76";
let option = {
    cors: {
        origin: origin,
        methods: ["GET", "POST"],
        allowedHeaders: ["my-custom-header"],
        credentials: true
    }
}
// 在线用户列表
let userlist = [];
//消息列表
let msglist = [];
// 创建实例
let io = require("socket.io")(serve, option);
// 监听连接
io.on("connection", (ctx) => {
    console.log("有新用户链接了");
    // 用户登录
    ctx.on("login", (data) => {
        // 判断在线列表是否已存在该用户
        let result = userlist.some((item) => {
            return item.user == data.user;
        })
        if (!result) {
            userlist.push({
                user: data.user,
                username: data.userName,
                image: data.userHeader
            });
            // 向所有用户发送通知有人加入了群聊
            io.emit("systemMsg", {
                type: "all",
                message: `${data.userName}加入了群聊、大家快欢迎他/她吧!`,
                deep: 3
            })
            console.log(`${data.userName}加入了群聊、大家快欢迎他/她吧!`);
            // 发送聊天数据
            io.emit("serveSend", msglist);
        }
        io.emit("online", userlist);
        console.log(`${data.user}登录了`);
    })
    //用户退出
    ctx.on("quit", (user) => {
        userlist.forEach((item, index) => {
            if (item.user == user) {
                console.log(`${user}离开了`);
                // 向所有用户发送通知有人离开了群聊
                io.emit("systemMsg", {
                    type: "all",
                    message: `${item.username}离开了群聊`,
                    deep: 2
                })
                userlist.splice(index, 1);
            }
        })
        //用户离开重新返回在线列表
        io.emit("online", userlist);
    }),
        //用户发送消息
        ctx.on("userSend", (data) => {
            msgFun(data);
            msglist.push(data);
            io.emit("serveSend", msglist);
        })
})

//<------聊天模块

app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
//解决跨域请求问题
app.all("/*", async function (req, res, next) {
    console.log(req.url);
    res.header({
        'Access-Control-Allow-Credentials': true,
        'Access-Control-Allow-Origin': req.headers.origin || '*',
        'Access-Control-Allow-Headers': 'content-type,token',
        'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS',
        'Content-Type': 'application/json; charset=utf-8'
    });
    if (req.method === "OPTIONS") {
        res.status(200).send("OK")
        // eslint-disable-next-line no-console
        console.log("has option")
    } else {
        let url = req.url.split("?")[0];
        if (url == "/login" ||url=="/signadd" || url == "/deleteToken"||url=="/addError"|| new RegExp("/header").test(url) || new RegExp("/uploads").test(url) ) {
            next()
        } else {
            let tokenReg = JSON.parse(await findToken(req.headers.token));
            console.log(tokenReg);
            if (tokenReg.code != 1000) {
                res.end(JSON.stringify(tokenReg))
            } else {
                next()
            }
        }
    }
});
// 上传文件保存目录及命名
let store = multer.diskStorage({
    // destination:"./uploadFile/image",
    destination: function (req, file, callBack) {
        console.log(req.route.path, 123);
        if (req.route.path == "/upload") {
            callBack(null, "./uploadFile/uploads");
        } else {
            callBack(null, "./uploadFile/header");
        }
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname)
    }
})
// 静态资源服务器
app.use(express.static(path.join(__dirname, "uploadFile")))
// 使用设置
let upload = multer({
    storage: store
});
// 更新信息
app.post("/userChage", userChage)
// 上传图片 
app.post("/upload", upload.array("avatar", 5), fileFun)
// 上传头像
app.post("/uploadheader", upload.array("avatar", 1), fileFun)
// 添加用户
app.post("/signadd", signAdd);
// 修改用户信息
app.post("/datumChange", datumChange);
// 添加日志信息
app.post("/log", logFun);
//修改用户积分信息
app.post("/integralChange", integralChange);
//添加数据
app.post("/add", addFun);
//添加消费记录
app.post("/expenseAdd", expenseAdd);
//修改数据
app.post("/change", changeFun);
//删除数据
app.post("/remove", removeFun);
//更改权限
app.post("/changeControl", changeControl);
//删除用户
app.post("/removeUser", removeUser);
// 修改邮件状态信息
app.post("/changeMsg", changeMsg);
// 发送邮件
app.post("/addSystem", addSystem);
// 获取日志信息
app.get("/getlog", logFind);
// 获取相册列表
app.get("/getImage", getImage);
// 用户登录
app.get("/login", login);
// 获取用户信息
app.get("/userFind", userFind)
// 获取数据信息
app.get("/getData", getData)
app.get("/getexpense", getExpense)
app.get("/getSysList", getSysList)
//添加结缘
app.post("/addLove", addLove);
//获取结缘信息
app.get("/getLove", getLove);
//删除结缘信息
app.get("/delLove", delLove);
//修改结缘信息
app.get("/changeLove", changeLove);
//删除token
app.get("/deleteToken", deleteToken);
//捕获异常
app.post("/addError", addError);
serve.listen(9527);